﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SaaS.Core.Authorization;
using Microsoft.AspNetCore.Mvc;
using XCore.Authorization;
using XCore.Extensions;
using Web.System.Services.Sites;
using XCore.Domain.Data;

namespace Web.System.Controllers.Sites
{
    /// <summary>
    /// 站点
    /// </summary>
    [Route("api/site/[controller]/[action]")]
    [ApiController]
    public class SiteController : SystemControllerBase
    {
        private readonly SiteAppService _siteAppService;
        /// <summary>
        /// 构造
        /// </summary>
        public SiteController(SiteAppService siteAppService)
        {
            _siteAppService = siteAppService;
        }

        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        [HttpPost, Permission(PermissionNames.Site_Tenant_Query)]
        public ActionResult List([FromForm]string name)
        {
            var query = SDC.Sites.Where(name, c => c.Name == name);
            return PageResult(query.OrderByDescending(c => c.CreationTime), c => new
            {
                c.Id,
                c.IP,
                c.CreationTime,
                c.Domain,
                c.Name,
                c.SecretKey,
            });
        }
        /// <summary>
        /// 客户信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet, Permission(PermissionNames.Site_Tenant_Query)]
        public ActionResult Info(int id)
        {
            return Ok(SDC.Sites.Where(c => c.Id == id).Select(c => new
            {
                c.Id,
                c.Name,
                c.Domain,
                c.IP,
                c.CreationTime,
            }).FirstOrDefault());
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="id"></param>
        /// <param name="name"></param>
        /// <param name="domain"></param>
        /// <param name="connectionString"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        [HttpPost, Permission(PermissionNames.Site_Tenant)]
        public ActionResult Save([FromForm]int? id, [FromForm]string name, [FromForm]string domain, [FromForm]string connectionString, [FromForm] DatabaseType type)
        {
            if (id.HasValue)
            {
                return Ok(_siteAppService.Edit(id.Value, name, domain, connectionString, type));
            }
            else
            {
                return Ok(_siteAppService.Create(name, domain));
            }
        }
        /// <summary>
        /// 日志跟踪
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        [Permission(PermissionNames.Site_Tenant_Query)]
        public ActionResult Logs(int siteId)
        {
            return Ok();
        }

    }
}